package com.nowcoder.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.result.Row;
import com.nowcoder.community.entity.Comment;
import com.nowcoder.community.entity.PageEntity;
import com.nowcoder.community.mapper.CommentMapper;
import com.nowcoder.community.service.ICommentService;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ChenJH
 * @since 2022-12-26
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService, CommunityConstant {
    @Autowired
    SensitiveFilter sensitiveFilter;
    @Autowired
    DiscussPostServiceImpl discussPostService;

    @Override
    public Page<Comment> findCommentsByEntity(int entityType, int entityId, PageEntity pageEntity) {
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getEntityType, entityType);
        wrapper.eq(Comment::getEntityId, entityId);
        wrapper.orderByAsc(Comment::getCreateTime);
        wrapper.eq(Comment::getStatus, 0);
        Page<Comment> page = page(pageEntity.toPage(), wrapper);
        return page;
    }

    @Override
    public long findCommentCount(int entityType, int entityId) {
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getEntityType, entityType);
        wrapper.eq(Comment::getEntityId, entityId);
        return count(wrapper);
    }

    @Override
    @Transactional
    public boolean addComment(Comment comment) {
//
        if (comment == null) {
            throw new IllegalArgumentException();
        }
//       添加评论
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        comment.setContent(sensitiveFilter.filter(comment.getContent()));
        boolean b = save(comment);
//        更新评论数量  只有针对帖子的评论才跟新
        if (comment.getEntityType() == ENTITY_TYPE_POST) {
//            因为评论 表中有对应的帖子id 这样就可以通过 帖子id查询到 帖子下面有多评论 再修改帖子的属性
            long count = findCommentCount(comment.getEntityType(), comment.getEntityId());
            discussPostService.updateCommentCount(comment.getEntityId(), count);
        }
        return b;
    }
}
